<?php #title = Заказы;

		

	$deliveries = array( 'self' => 'Самовывоз', 'courier' => 'Курьер' );
	$limit = 20;


	if( isset( $_GET['basket_id'] ) )
	{

//		$sql = 'SELECT sql_calc_found_rows sb.id AS basket_id, o.id AS order_id,  u.id AS user_id, sb.date_order, u.name, u.email, sb.delivery_type, sb.status, sb.site_full_info
//				FROM `store_baskets` AS `sb`
//					INNER JOIN `users` AS `u` ON `u`.`id` = `sb`.`user_id`
//						LEFT JOIN store_orders AS o ON o.basket_id = sb.id
//							WHERE `sb`.`id` = '.$_GET['basket_id'];

                
                /* shit
		$path = __DIR__ .'/cache/'. md5($sql).'.txt';

		if( file_exists($path) ) {
			$result = unserialize(file_get_contents($path));
		} else {
			$conn->query($sql);
			$result = $conn->fetch();
			file_put_contents($path, serialize($result));
		}
                 * 
                 */
            
            $sql = 'SELECT sql_calc_found_rows sb.id AS basket_id, o.id AS order_id,  u.id AS user_id, sb.date_order, u.name, u.email, sb.delivery_type, sb.status 
				FROM `store_baskets` AS `sb`
					INNER JOIN `users` AS `u` ON `u`.`id` = `sb`.`user_id`
						LEFT JOIN store_orders AS o ON o.basket_id = sb.id
							WHERE `sb`.`id` = '.$_GET['basket_id'];
                
                
                
                $conn->query($sql);
			$result = $conn->fetch();
			
		if( $order = $result )
		{
			$adress = $user->getData( 'adress', $order->user_id );
			$phone = ( $phone = array_shift( $user->getData( 'phone', $order->user_id ) ) ) ? $phone : 'не указан';
			$adress = ( $adress = array_shift( $user->getData( 'adress', $order->user_id ) ) ) ? $adress : 'нет';
			$adress = ( $adress = array_shift( $user->getData( 'adress', $order->user_id ) ) ) ? $adress : 'нет';


			$delivery_type = isset( $deliveries[$order->delivery_type] ) ? $deliveries[$order->delivery_type] : $deliveries['courier'];
			$products = getBasketProducts( $order->basket_id , $need_host = false, $order->delivery_type );
			
			$view->gText .= '
			
				<div class="main_order_data">
					<h2>Номер заказа: '.( $order->order_id ? $order->order_id : $order->basket_id ).'</h2>
					<h2 style="color: grey;">Cайт источник: '.( $order->site_full_info ? $order->site_full_info : '' ).'</h2>
					<div class="order_data">
						Дата: '.$order->date_order.'<br/>
						Ф.И.О: <b>'.$order->name.'</b><br/>
						Контактный номер: <b>'.$phone.'</b><br/>
						E-mail: <b>'.$order->email.'</b><br/>
						Способ доставки: <b>'.$delivery_type.'</b><br/>
						Адрес доставки: <b>'.$adress.'</b><br/>
						Статус: <select class="change_order_status" basket_id="'.$order->basket_id.'">'.getOrderStatus( $order->status ).'</select> <img class="status_ok" src="/inc/images/admin/ok.png" /><br/>
					</div>
						<h2>Товары</h2>
						'.$products['list'].'
				</div>';
		
		}

	}
	else
	{
		$orders = array();
		$html_list = '';
		$basket_ids = array();
		$view->paginator_index = isset( $_GET['pnum'] ) ? $_GET['pnum'] - 1 : 0;


		// запрос с получением общего количества строк

        $conn->query('
			SELECT sql_calc_found_rows sb.id AS basket_id, o.id AS order_id, u.id AS user_id, sb.date_order, u.name, sb.delivery_type, sb.status,
				( SELECT SUM( sbv.product_total_price ) FROM store_basket_view sbv WHERE sbv.basket_id = sb.id ) AS total_price,
				( SELECT count(sbp2.basket_id) FROM store_basket_products sbp2 WHERE sbp2.basket_id = sb.id) AS count
					FROM store_baskets AS sb
						INNER JOIN users AS u ON u.id = sb.user_id
						LEFT JOIN store_orders AS o ON o.basket_id = sb.id
							WHERE sb.status != "basket"
								GROUP BY sb.id
									ORDER BY o.id DESC, sb.id DESC
										LIMIT '.$view->paginator_index * $limit.', '.$limit
        );

		$conn->query('SELECT found_rows() AS `num`', 0, 1 );
		$total = $conn->fetch(1);
		$count_orders = $total ? $total->num : 0;


//		$conn->query('
//			SELECT sb.id AS basket_id, o.id AS order_id, u.id AS user_id, sb.date_order, u.name, sb.delivery_type, sb.status,
//				( SELECT SUM( sbv.product_total_price ) FROM store_basket_view sbv WHERE sbv.basket_id = sb.id ) AS total_price,
//				( SELECT count(sbp2.basket_id) FROM store_basket_products sbp2 WHERE sbp2.basket_id = sb.id) AS count
//					FROM store_baskets AS sb
//						INNER JOIN users AS u ON u.id = sb.user_id
//						LEFT JOIN store_orders AS o ON o.basket_id = sb.id
//							WHERE sb.status != "basket"
//								GROUP BY sb.id
//									ORDER BY o.id DESC, sb.id DESC
//										LIMIT '.$limit
//		);
		
		while( $row = $conn->fetch() )	{
			$orders[$row->basket_id] = $row;
			$basket_ids[] = $row->basket_id;
		}
		
		if( count( $orders ) ) {
			foreach( $orders as $basket_id => $order )
			{
				$delivery_type = isset( $deliveries[$order->delivery_type] ) ? $deliveries[$order->delivery_type] : $deliveries['courier'];
				$delivery = isset( $deliveries[$order->delivery_type] ) ? $order->delivery_type : 'courier';
				$order_cost = $order->total_price + calculateCostDelivery( $basket_id, $delivery );


				$html_list .= '
					<tr class="'.$order->status.'">
						<td class="order_number"><a href="?p=orders&basket_id='.$order->basket_id.'">'.( $order->order_id ? $order->order_id : $order->basket_id ).'</a></td>

						<td>'.$order->date_order.'</td>
						<td>'.$order->name.'</td>
						<td>'.$delivery_type.'</td>
						<td class="total_price">'.getPriceFormat( $order_cost ).'</td>
						<td class="pr_count">'.$order->count.'</td>
						<td><select class="change_order_status" basket_id="'.$order->basket_id.'">'.getOrderStatus( $order->status ).'</select> <img class="status_ok" src="/inc/images/admin/ok.png" /></td>
					</tr>';
					// echo $order->delivery_type.'<br/>';
			}
		}
		
		$view->gText .= '
			<div class="orders_table">
				<table>
					<tr>
						<td>Номер</td>
						<td>Время заказа</td>
						<td>Покупатель</td>
						<td>Дост.</td>
						<td>Стоимость</td>
						<td>Кол.</td>
						<td class="status">Статус</td>
					</tr>
					'.$html_list.'
				</table>
			</div>'.$load->block( 'pagination', array(
									'total'			=> $count_orders,
									'limit'			=> $limit, 
								// 	'url_before'	=> $url_before, 
								//	'url_after'		=> '?p=orders' 
								) );
									
	}
		
		
	function getOrderStatus( $status )
	{
		$option_list = '';
		$statuses = array( 
				'order'		=> array( 'text' => 'Активный', 'class' => 'green' ),
				'done'		=> array( 'text' => 'Выполнен', 'class' => 'yellow' ),
				'cencel'	=> array( 'text' => 'Отменён', 'class' => 'red' ),
			);
			
		foreach( $statuses as $st => $data )
			$option_list .= '<option'.( ( $status == $st ) ? ' selected="selected"' : '' ).' value="'.$st.'" >'.$data['text'].'</option>';
		return $option_list;
	}


	
	 $adresses = $user->getData( 'adress' );
	 $s_names = $user->getData( 'second_name' );
	 echo '<pre>';
//	 print_r($s_names);
	

	$conn->query('
		SELECT sql_calc_found_rows sb.id AS basket_id, u.id AS user_id, sb.date_order, u.name, sb.delivery_type, sb.status
		FROM `store_baskets` AS sb
		INNER JOIN users AS u ON u.id = sb.user_id
		WHERE sb.status != "basket"
		LIMIT 20
	'); 
	
	
//	if( count( $basket_ids ) > 0 )
//	{
// 		$conn->query('
//			SELECT basket_id, ( ( price_retail * count ) + ( price_inst * count_inst  ) + ( price_vip * count_vip ) ) AS total
//			FROM store_basket_view WHERE basket_id IN ( '.implode( ',', $basket_ids ).' )');
//		while( $row = $conn->fetch() )
//		{
//			$total_count[$row->basket_id] = $row->total;
//		}
//	} 
//
//	
//	 	foreach( $orders as $basket_id => $order )
//	{
//		$s_name = isset( $s_names[$order->user_id] ) ? ' '.$s_names[$order->user_id] : '';
//		$html_list .= '			
//			<tr>
//				<td>'.$order->basket_id.'</td>
//				<td>'.$order->date_order.'</td>
//				<td>'.$order->name.$s_name.'</td>
//				<td>'.$deliveries[$order->delivery_type].'</td>
//				<td>'. $row->total_price.'</td>
//				<td>'.$statuses[$order->status].'</td>
//			</tr>';
//	} 
//
//	 $orders[$row->basket_id] = $row;
//	$basket_ids[] = $row->basket_id;
